<template>
  <div class="mainua">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>{{ titleName }}</span>
          </div>
        </div>
        <div class="main_tile boxdq marginTop10">
          <div class="main_tile_l"></div>
        </div>
        <div class="maincla_form">
          <el-form
            ref="form"
            :rules="rules"
            :model="detail"
            label-width="120px"
          >
            <!-- 学校名称、负责人、手机号、域名、选择供应商、学校logo图片、 -->
            <el-form-item label="代理商名称" prop="agent_name">
              <el-input v-model="detail.agent_name"></el-input>
            </el-form-item>
            <el-form-item label="负责人" prop="manager_name">
              <el-input
                v-model="detail.manager_name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="detail.mobile" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="域名" prop="domain_name">
              <el-input v-model="detail.domain_name" autocomplete="off">
                <template slot="append">.jyt.cadj.cn</template>
              </el-input>
            </el-form-item>
            <el-form-item label="域名预览" v-if="detail.domain_name">
              <span>{{ detail.domain_name }}.jyt.cadj.cn</span>
            </el-form-item>
            <!-- <el-form-item label="选择供应商" prop="model">
              <el-select multiple  v-model="detail.model" placeholder="选择供应商" @change="changeModel" :disabled="iseditStatus">
                <el-option v-for="item in userType" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="所在地" prop="add">
              <el-select v-model="firstId" placeholder="" @change="selectAction($event, 'firstId')">
                <el-option v-for="item in firstList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <el-select v-model="secondId" placeholder="" @change="selectAction($event, 'secondId')">
                <el-option v-for="item in secondList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <el-select v-model="thiredId" placeholder="" @change="selectAction">
                <el-option v-for="item in thiredList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="所在地" prop="province_code">
              <el-cascader
                v-model="detail.province_code"
                :options="options"
                :props="props"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>

            <el-form-item label="公司地址" prop="address">
              <el-input
                v-model="detail.address"
                class="address"
                type="textarea"
                :rows="2"
              ></el-input>
            </el-form-item>
            <el-form-item label="资质">
              <el-upload
                :action="uploadPath"
                list-type="picture-card"
                :data="{ store: 'saas/contract' }"
                style="min-height: 120px"
                :on-success="successpdf"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :file-list="filelist"
                :on-error="onError"
                :on-progress="onProgress"
              >
                <span slot="default">
                  <svg
                    aria-hidden="true"
                    class="main_page_svg"
                    width="32"
                    height="27"
                  >
                    <use xlink:href="#icon-commodit_camera" />
                  </svg>
                </span>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
            <!-- <el-form-item label="负责人邮箱" prop="email">
              <el-input v-model="detail.email" autocomplete="off"></el-input>
            </el-form-item>


            <el-form-item label="客服选择" prop="cust_id">
              <el-select
                v-model="detail.cust_id"
                placeholder="客服选择"
              >
                <el-option
                  v-for="item in custType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              v-if="openshow"
              label="系统还原"
              prop="open_reduction"
            >
              <el-switch
                v-model="detail.open_reduction"
                :active-value="1"
                :inactive-value="0"
                active-color="#03A98E"
              >
              </el-switch>
            </el-form-item>

            <el-form-item v-if="chose" prop="product_ids" label="应用助手">
              <el-checkbox-group v-model="detail.product_ids">
                <el-checkbox
                  v-for="(item, index) in product_ids"
                  :key="index"
                  :label="item.id"
                  :value="item.name"
                  >{{ item.name }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>

            <el-form-item
              label="绑定批发"
              prop="bind_dispatch"
              v-if="showDispatch"
            >
              <el-select
                v-model="detail.bind_dispatch"
                placeholder="请选择"
                style="width: 350px"
              >
                <el-option label="无" value=""> </el-option>
                <el-option
                  v-for="item in dispatchList"
                  :key="item.id"
                  :label="item.company_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item v-if="showXuF" label="续费金额" prop="renewal_money">
              <el-input
                v-model="detail.renewal_money"
                type="number"
                min="0"
                style="width: 350px"
              />
            </el-form-item>

            <el-form-item
              v-if="showYongj"
              label="佣金比例"
              prop="commission_rate"
            >
              <el-input
                v-model="detail.commission_rate"
                type="number"
                min="0"
                style="width: 350px"
              >
                <template slot="append"
                  >‰</template
                >
              </el-input>
            </el-form-item>

            <el-form-item label="服务时间" prop="serveTime">
              <el-date-picker
                v-model="detail.serveTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="timestamp"
                @change="selectDate"
                :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
           
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="detail.remark"
                class="address"
                type="textarea"
                :rows="2"
              ></el-input>
            </el-form-item>

            <el-form-item label="服务状态">
              <el-switch
                v-model="detail.status"
                :active-value="1"
                :inactive-value="0"
                active-color="#03A98E"
              >
              </el-switch>
            </el-form-item> -->

            <el-form-item>
              <div>
                <el-button :disabled="disabled" type="primary" @click="onSubmit"
                  >保存</el-button
                >
                <el-button @click="$router.back()">取消</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { menuType } from "@/api/user/userMenu";
import { uploadPath } from "@/api/currency";
import { lists } from "../../assets/json/area_2.json";
import {
  getCompanyDetail,
  // 获取代理商详细信息
  queryInfo,
  addCompany,
  editCompany,
  getAllCompany,
  getCustList,
} from "@/api/user/userList";
import { regionListByPid } from "@/api/global/provinces";
import { list } from "@/api/user/userList";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
export default {
  data() {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    var checkYJ = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("佣金比例不能为空"));
      } else {
        if (value < 0) {
          return callback(new Error("佣金比例不能为负值"));
        } else {
          callback();
        }
      }
    };
    var checkXuF = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("缴费金额不能为空"));
      } else {
        if (value < 0) {
          return callback(new Error("缴费金额不能为负值"));
        } else {
          callback();
        }
      }
    };
    var checkAdd = (rule, value, callback) => {
      if (this.firstId && this.secondId && this.thiredId) {
        return callback();
      } else {
        return callback(new Error("请选择所在地"));
      }
    };
    let _this = this;
    return {
      titleName: "",
      uploadPath,
      filelist: [],
      dialogVisible: false,
      dialogImageUrl: "",

      detail: {
        commission_rate: 6,
        cust_id: "",
        open_reduction: 0,
        product_ids: [5, 6, 7, 8, 9],

        contract: [],
        province_code: [],
        model: "",
        domain_name: "",
        mobile: "",
        manager_name: "",
        address: "",
        agent_name: "",
      },
      rules: {
        agent_name: [
          { required: true, message: "请输入代理商名称", trigger: "blur" },
        ],
        manager_name: [
          { required: true, message: "请输入负责人名称", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入号码", trigger: "blur" },
          { validator: checkPhone, message: "号码格式错误", trigger: "change" },
        ],
        // commission_rate: [
        //   { validator: checkYJ, required: true, trigger: "change" }
        // ],
        // renewal_money: [
        //   { validator: checkXuF, required: true, trigger: "blur" }
        // ],
        // add: [{ validator: checkAdd, required: true, trigger: "change" }],
        province_code: [
          { required: true, message: "请选择所在地地址", trigger: "change" },
        ],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        // model: [
        //   { required: true, message: "请选择客户类型", trigger: "change" }
        // ],
        domain_name: [
          { required: true, message: "请输入域名", trigger: "blur" },
        ],
        serveTime: [
          {
            type: "array",
            required: true,
            message: "请选择服务时间",
            trigger: "change",
          },
        ],
      },
      dispatchList: [], //城配要绑定的批发
      showDispatch: false, //是否显示批发列表
      showYongj: false, //批发城配显示佣金
      showXuF: false, //软件显示续费金额
      firstList: [],
      secondList: [],
      thiredList: [],
      base_address: "",
      firstId: "",
      secondId: "",
      thiredId: "",
      userType: [], //客户类型
      custType: [], //选择客服
      iseditStatus: false, //是否为编辑状态
      openshow: true, //新增用户才会显示系统还原
      chose: false,
      product_ids: [
        {
          name: "采购助手",
          id: 5,
        },
        {
          name: "供应商助手",
          id: 6,
        },
        {
          name: "司机助手",
          id: 7,
        },
        {
          name: "业务员助手",
          id: 8,
        },
        {
          name: "超管助手",
          id: 9,
        },
      ],

      value: [],
      options: lists,
      props: {
        value: "id",
        label: "name",
      },
      disabled: false, // 上传资质时，下面的提交按钮必须失效，只有等上传成功或者失败后才能点击
    };
  },
  mounted() {
    // console.log(this.options)
    var id = this.$route.query.id;
    if (id) {
      this.getData(id);
      this.titleName = "编辑客户";
      this.iseditStatus = true;
      this.openshow = false;
      this.$route.meta.bread = "客户列表,编辑客户";
    } else {
      this.titleName = "新增客户";
      this.openshow = true;
      this.$route.meta.bread = "客户列表,新增客户";
      this.getProvinces("0", 1);
    }
    // this.getCompanyList();
    // this.getUserType();
    // this.getCustList();
  },
  methods: {
    //上传合同
    successpdf(response) {
      if (!response.errcode) {
        this.detail.contract.push({
          path: response.data.path,
          src: response.data.src,
        });
        this.disabled = false;
      } else {
        this.disabled = false;
        this.$message.error(response.errmsg);
      }
    },
    onError() {
      this.disabled = false;
    },
    //上传图片-查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //删除
    handleRemove(file) {
      if (file.response) {
        this.detail.contract = this.detail.contract.filter((i) => {
          return i.path != file.response.data.path;
        });
      } else {
        this.detail.contract = this.detail.contract.filter((i) => {
          return i.path != file.path;
        });
      }
      console.log(this.detail.contract);
    },
    //获取客户类型
    getUserType() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      menuType(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.userType = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //获取客服列表
    getCustList() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name), { cust_role: 1 }) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { cust_role: 1 }
      );
      getCustList(data).then((res) => {
        if (res.errcode == 0) {
          this.custType = res.data.list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    getData(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name), { id }) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id }
      );
      queryInfo(data).then((res) => {
        if (res.errcode == 0) {
          let { data } = res || {};
          let {
            agent_name,
            manager_name,
            address,
            domain_name,
            mobile,
            province_code,
            city_code,
            country_code,
          } = data;
          this.detail.agent_name = agent_name;
          this.detail.manager_name = manager_name;
          this.detail.address = address;
          this.detail.domain_name = domain_name;
          this.detail.mobile = mobile;
          this.detail.province_code = [province_code, city_code, country_code];
          // this.thiredId = data.base_address
          // this.firstId = 130000
          let qualifications = data.qualifications;
          if (qualifications) {
            JSON.parse(qualifications).forEach((is) => {
              this.filelist.push({
                name: "",
                path: is.path,
                url: is.src,
                id: is.uid,
              });
            });
          }
          this.detail.contract = JSON.parse(qualifications);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    selectDate(e) {
      this.detail.serveTime = e;
      this.detail.start_time = e[0] / 1000;
      this.detail.end_time = e[1] / 1000;
    },
    //选择客户类型
    changeModel(e) {
      if (e == 2 || e == 3) {
        this.showDispatch = true;
      } else {
        this.showDispatch = false;
      }
      if (e == 1 || e == 2) {
        this.showYongj = true;
      } else {
        this.showYongj = false;
      }
      if (e == 3) {
        this.showXuF = true;
        this.chose = true;
        this.detail.open_reduction = 1;
      } else {
        this.showXuF = false;
        this.chose = false;
        this.detail.open_reduction = 0;
      }
    },

    //获取城配需要的批发商列表
    getCompanyList() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name), { model: 1 }) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { model: 1 }
      );
      getAllCompany(data).then((res) => {
        if (res.errcode == 0) {
          this.dispatchList = res.data.list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    getProvinces(pid, lv) {
      if (pid) {
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name), { pid }) +
                apiUrl().appsecret
            ),
          },
          apiUrl().name,
          { pid }
        );
        regionListByPid(data).then((res) => {
          if (res.errcode == 0) {
            if (lv == 1) {
              this.firstList = res.data.list;
            } else if (lv == 2) {
              this.secondList = res.data.list;
            } else if (lv == 3) {
              this.thiredList = res.data.list;
            }
          } else {
            this.$message.error(res.errmsg);
          }
        });
      }
    },
    selectAction(e, type, item) {
      if (type == "firstId") {
        this.secondList = [];
        this.secondId = null;
        this.thiredList = [];
        this.thiredId = null;
        this.getProvinces(e, 2);
      } else if (type == "secondId") {
        this.thiredList = [];
        this.thiredId = null;
        this.getProvinces(e, 3);
      } else {
        this.detail.base_address = e;
      }
      this[type] = e;
      console.log(this.detail.base_address);
    },
    handleChange(e) {
      if (e) {
        // let province_code = null
        // province_code = e.join(',')
        // this.detail.province_code = province_code
        this.$nextTick(() => {
          this.$refs.form.clearValidate(["add"]);
        });
      }
    },
    onProgress() {
      this.disabled = true;
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 将资质数组转字符串
          let filelist = [];
          filelist = [...this.detail.contract];
          let qualifications = filelist
            ? JSON.stringify(filelist)
            : JSON.stringify([]);
          debugger;
          let datas = {
            agent_name: this.detail.agent_name,
            manager_name: this.detail.manager_name,
            mobile: this.detail.mobile,
            domain_name: this.detail.domain_name,
            // base_address: this.detail.base_address,
            province_code: this.detail.province_code[0],
            city_code: this.detail.province_code[1],
            country_code: this.detail.province_code[2],
            address: this.detail.address,
            qualifications: qualifications,
          };
          let params = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name), datas) +
                  apiUrl().appsecret
              ),
            },
            apiUrl().name,
            datas
          );
          let msg = null;
          if (this.$route.query.id) {
            params.action = "update";
            params.id = this.$route.query.id;
            msg = "修改成功";
          } else {
            params.action = "add";
            msg = "新增成功";
          }
          addCompany(params).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: msg,
                type: "success",
              });
              this.$router.back();
            } else {
              this.$message.error(res.errmsg);
            }
          });
          return;
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.el-form-item__content {
  margin-left: 0px !important;
}

/deep/.el-form-item__content > .el-input {
  width: 350px;
}

/deep/.el-select {
  width: 114px;

  .el-input__inner {
    width: 100% !important;
  }
}

.btns {
  margin: 20px 110px 0;

  button {
    margin-right: 10px;
  }
}

.address {
  max-width: 350px;
}

/deep/.el-upload--picture-card {
  position: relative !important;
}

// /deep/ .el-select {
//   width: 350px !important;
// }
/deep/ .el-form-item__error {
  left: 120px !important;
}

/deep/.el-upload-list--picture-card .el-upload-list__item:first-child {
  margin-left: 0 !important;
}

/deep/.el-input {
  width: 350px;
}
</style>
